package pdm.traj.query.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pdm.traj.entity.TrackPoint2;
import pdm.traj.entity.TrajQuery;
import pdm.traj.service.TrajDataService;
import pdm.traj.util.TrackPointUtil;

/**
 * 直接从文本文件中查询，用于做查询性能比较的baseline
 * 功能杠杠的，亮瞎亲的双眼
 * 亲的存储查询机制如果连这个都比不过就去呵呵吧（当然比不过这个的概率也是很高的！）
 * @author gaozhenlong
 * @Date 2014-1-12
 */
public class FileQuery implements TrajDataService {
	private String srcPath;
	private TrajQuery query;
	private Date startTime, endTime;
	private boolean checksid;
	private boolean checkuid;
	
	public void init() {
		startTime = TrackPointUtil.getStartTime(query);
		endTime = TrackPointUtil.getEndTime(query);
		checksid = !(query.getSids() == null || (query.getSids().size() == 0));
		checkuid = !(query.getUids() == null || (query.getUids().size() == 0));
	}
	
	@Override
	public List<TrackPoint2> queryMultiTrajTPList(TrajQuery query) {
		this.query = query;
		init();
		if (srcPath == null) {
			return null;
		}
		if (startTime == null || endTime == null) {
			return null;
		}
		
		File file = new File(srcPath);
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			List<TrackPoint2> result = new ArrayList<TrackPoint2>();
			while (br.ready()) {
				//read a line 
				String tpStr = br.readLine();
				TrackPoint2 tp = TrackPoint2.parseTP(tpStr);
				Date d = TrackPointUtil.getTs(tp);
				if (d != null && d.after(startTime) && d.before(endTime)) {
					if (checkuid && query.getUids().contains(tp.getId())) {
						if (checksid && query.getSids().contains(TrackPointUtil.getSid(tp))) {
							result.add(tp);
						} else if (!checksid){
							result.add(tp);
						}
					} else if (!checkuid) {
						result.add(tp);
					}
				}
			}
			return result;
		} catch (FileNotFoundException e) {
//			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void setSrcPath(String srcPath) {
		this.srcPath = srcPath;
	}
	
}
